package com.yc.fav.servlet;

import com.google.gson.Gson;
import com.yc.fav.entity.FavFavorite;
import com.yc.fav.entity.Result;
import com.yc.fav.service.BizException;
import com.yc.fav.service.impl.FavFavoriteServiceImpl;
import com.yc.fav.util.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 添加收藏链接
 */
@WebServlet("/add.do")
public class AddServlet extends HttpServlet {

    // 业务层对象
    private FavFavoriteServiceImpl service = new FavFavoriteServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        // 读取数据, 将数据封装到实体对象中(类型转型, 名字映射)
        FavFavorite ff = Utils.asBean(req.getParameterMap(), FavFavorite.class);

//        String flabel = req.getParameter("flabel");
//        String furl = req.getParameter("furl");
//        String fdesc = req.getParameter("fdesc");
//        String ftags = req.getParameter("ftags");
//        FavFavorite ff = new FavFavorite();
//        ff.setFdesc(fdesc);
//        ff.setFlabel(flabel);
//        ff.setFurl(furl);
//        ff.setFtags(ftags);
        Result result;
        // 调用业务层方法
        try {
            service.add(ff);
            result = new Result(1, "添加链接成功!", ff);
        } catch (BizException e) {
            e.printStackTrace();
            result = new Result(0, e.getMessage(), null);
        }
        String toJson = new Gson().toJson(result);
        resp.getWriter().append(toJson);
    }

}
